import _ from "underscore";
import moment from "moment";

import Vue from 'vue';
import api from '../api';

import {
  mapState,
  mapActions
} from 'vuex'

export const sound = {
  computed: {
    ...mapState({
      uid: state => state.vux.uid,
      mp3Arr: state => state.z39.mp3Arr,
      mp3Curr: state => state.z39.mp3Curr,
      mp3Update: state => state.z39.mp3Update
    })
  },
  methods: {
    onPlay(item, index) {
      if (!item.url && item.localId) {
        if (!Vue.device.isWechat) return this.$vux.toast.show({ text: "微信中播放", type: 'warn' });
        return this.playRecord(item.localId);
      }
      console.log("item:", JSON.stringify(item));
      if (!item.urllocal && !item.url && !this.isInApp) {
        return this.$vux.toast.show({ text: "请APP播放", type: 'warn' });
      }
      this.playerShow = true;
      if (isApp && item.file) {
        this.playType = 1;
        mp3player.initMp3(this.playType);
        mp3player.startPlay(item.file);
      } else {
        this.playType = 2;
        mp3player.initMp3(this.playType);
        var audio = document.querySelector('.d_record .myVideo');
        audio.src = item.urllocal || item.url;
        mp3player.playpause();
      }

      this.currMp3 = item;
      // console.log("mp3 item: ", isApp, JSON.stringify( item ) ,audio.src ) ;
    },
    onStart() {
      if (!this.uid) {
        setTimeout(() => { this.mp3State = -1; }, 1000);
        return this.$vux.toast.show({ text: "请先登录", type: "warn" })
      }
      if (!isApp && !Vue.device.isWechat) {
        // 不支持录音就跳出逻辑,
      }
      this.audioCurr = { start: moment().format('HH:mm:ss'), duration: '00:00' };
      this.audioCurr.title = '录音 ' + moment().format('MM-DD HH:mm:ss');
      this.startTime = moment().valueOf();
      let num = 0;
      let _this = this;
      if (this.wxIntId != -1) clearInterval(this.wxIntId);
      this.wxIntId = setInterval(() => {
        num++;
        _this.audioCurr.duration = num.formatTime2();
        _this.percentSound = 100 - num * 100 / 60;
        if (num >= 59) _this.onStop();
      }, 1000);
      this.percentSound = 100;
      this.mp3State = 0; //播放动画

      if (Vue.device.isWechat) {
        this.doStartRecord();
      } else if (isApp) {
        try {
          startRecord();
        } catch (e) {
          this.mp3State = -1;
          this.$vux.toast.show({ text: "APP异常", type: "warn" })
          console.log("dcloud not ready")
        }
      } else {
        HZRecorder.get(function(rec) {
          if (rec.errno) {
            _this.state_say = false;
            return _this.$vux.toast.show({ text: rec.errmsg, type: "warn" });
          }
          console.log(rec)
          _this.recorder = rec;
          _this.recorder.start();
          // _this.getvideoprogress();
        });
      }
    },
    onStopAudio() {
      this.audioCurr.end = moment().format('HH:mm:ss');
      this.audioCurr.duration = ((moment().valueOf() - this.startTime) / 1000).formatTime2();
      this.clearWxRecInv();
    },
    onStop() {
      this.onStopAudio();
      if (Vue.device.isWechat) {
        this.doStopRecord(true);
      } else if (isApp) {
        try { stopRecord(); } catch (e) {
          this.mp3State = -1;
          this.$vux.toast.show({ text: "APP异常", type: "warn" })
          console.log("dcloud not ready")
        }
      } else {
        clearTimeout(this.recordTime);
        this.mp3State = -1;
        this.recorder.stop();
        this.audioCurr.end = moment().format('HH:mm:ss');
        this.playProgress = JSON.stringify(this.percentSound);
        let audio = this.recorder.getBlob();
        console.log(audio)
        this.audioCurr.audio = audio;
        this.doAudioAdd(this.audioCurr);
      }
    },
    onCancle() {
      this.clearWxRecInv();
      if (Vue.device.isWechat) {
        this.doStopRecord(false);
      } else if (isApp) {
        try { audioCancle(); } catch (e) {
          this.mp3State = -1;
          this.$vux.toast.show({ text: "APP异常", type: "warn" })
          console.log("dcloud not ready")
        }
      } else {
        this.recorder.stop();
        clearTimeout(this.recordTime);
        this.percentSound = 0;
        this.audioCurr.duration = "00:00";
        this.mp3State = -1;
      }
    },
    onDelClick(item, index) {
      console.log(item);
      try {
        audioDel(item.file);
      } catch (e) { console.log("dcloud not ready", e) };
      this.doAudioDel(item);
    },
    doStartRecord() {
      // let wx = Vue.wechat ;
      wx.startRecord();
      let _this = this;
      wx.onVoiceRecordEnd({
        complete: function(res) { // 录音时间超过一分钟没有停止的时候会执行 complete 回调
          _this.mp3State = 1;
          _this.audioCurr.localId = res.localId;
          _this.doWxAudioTask(res.localId);
          _this.onStopAudio();
          // _this.$vux.toast.text('APP录音更长,突破微信60秒限制', 'top');
        }
      });
    },
    doStopRecord(isSave) {
      // let wx = Vue.wechat ;
      let _this = this;
      wx.stopRecord({
        success: function(res) {
          if (isSave) {
            console.log("dev stopRecord:", res.localId)
            // alert("Record OK",res.localId);
            _this.audioCurr.localId = res.localId;
            _this.doWxAudioTask(res.localId);
          } else {

          }
        }
      });
    },
    clearWxRecInv() {
      clearInterval(this.wxIntId);
      this.wxIntId = -1;
      this.durationWX = '';
      this.mp3State = -1;
    },
    playRecord(id) {
      wx.playVoice({
        localId: id
      });
    },
    uploadVoice(id, ext) { //type =1,旧代码先现在serveid后上传. 2.先创建任务在下载
      let _this = this;
      let { aid, type } = ext;
      wx.uploadVoice({
        localId: id, // 需要上传的音频的本地ID
        isShowProgressTips: 1,
        success: function(res) {
          console.log("uploadVoice:", res);
          var serverId = res.serverId;
          // this.mp3Curr.url = serverId ; 
          if (type == 1) {
            _this.doAudioAdd({ serverId }).then(data => {
              if (data && data.errno == 0) _this.$vux.toast.show({ text: "上传成功", type: 'success' });
            });
          } else if (type == 2) {
            _this.doAudioSet({ serverId, id: aid, istask: 1 });
          }
        },
        fail: function(res) {
          alert(JSON.stringify(res))
        }
      });
    },
    deletetVoice(id) {},
    doAudiosGet() {
      let _this = this;
      api.audioGet().then(data => {
        if (data.errno != 0) return this.$vux.toast.show({ text: data.errmsg, type: 'warn' });
        data = data.data;
        this.audioArr = data;
        // _this.doMerge();
      })
    },
    doAudioAdd(tdata) {
      if (this.audioCurr.duration <= "00:01") return; //this.$vux.toast.show({ text: "时间太短", type: 'warn' })
      let ext = Object.assign(tdata || {}, this.audioCurr);
	  if (!ext.title) return ;
      if (localStorage.getItem("lastAppMp3") == ext.title) return;
      localStorage.setItem("lastAppMp3", ext.title);
      console.log("doAudioAdd dowith");
      //this.$vux.toast.show({ text: "doAudioAdd test", type: 'warn' });

      let tags = this.getTagExt(); //taskadd.vue中的逻辑 { created: moment().format('YYYY-MM-DD HH:mm') };
      let data = { sound: 1, title: ext.title, ext, tags };
      console.log("doAudioAdd", JSON.stringify(data));
      let _this = this;
      return this.taskAdd(data).then(data => {
        if (ext.localId) this.uploadVoice(ext.localId, { type: 2, aid: data.aid });
        else if (ext.file) audioUpload(Object.assign(tdata, { aid: data.aid, taskid: data.id, id: data.id, snd2txt: 1 }),api.token); //app上传音频使用
      });
      // return this.audioAdd(data);
    },
    doAudioSet(tdata) { //需要serveid 和 audioid.如果上传失败,需要继续上传.
      return api.audioSet(tdata).then(data => {

      })
    },
    doWxAudioTask(localId) {
      this.doAudioAdd()
    },
    audioAdd(tdata) {
      if (_.isEmpty(tdata)) return Promise.reject({ errno: 1001, msg: '数据为空' });
      let _this = this;
      return api.audioAdd(tdata).then(data => {
        if (data.errno != 0) return this.$vux.toast.show({ text: data.errmsg, type: 'warn' });
        data = data.data;
        tdata.id = data;
        // _this.audioArr.splice(0, 0, tdata);
        // _this.audioArr.push(tdata);
        _this.audioArr.unshift(tdata);
        _this.$forceUpdate();
        return Promise.resolve({ errno: 0, msg: '上传成功' });
      })
    },
    doAudioDel(item) {
      let _this = this;
      api.audioDel({ id: item.id }).then(data => {
        if (data.errno != 0) return this.$vux.toast.show({ text: data.errmsg, type: 'warn' });
        data = data.data;
        this.audioArr.splice(_this.audioArr.indexOf(item), 1);
        this.$vux.toast.show({
          text: "删除成功",
          type: 'success'
        })
      })
    },
  },
  watch: {
    "mp3Curr": function() { //多文件应用mixinsound会导致重复执行逻辑.
      console.log("mixin sound mp3Curr");
      this.doAudioAdd(this.mp3Curr);
    },
    "mp3Arr": function() {
      // this.doMerge();
    },
    "mp3Update": function() {
      return; //以前录音页面的逻辑,现在已经用不上.
      console.log("mp3Update record:", this.mp3Update);
      let temp;
      for (var i = this.audioArr.length - 1; i >= 0; i--) {
        temp = this.audioArr[i];
        if (this.mp3Update.id == temp.id) {
          for (var key in this.mp3Update) {
            temp[key] = this.mp3Update[key];
          }
          break;
        }
      };
    }
  }
}
